import Vue from 'vue'
import App from './App.vue'
import router from './router'

import 'styles/base.css'
import 'styles/iconfont.css'
// 导入 rem 的 js, 动态的设置了, 不同屏幕的html根元素的 font-size
import 'lib-flexible'
import axios from 'axios'
import moment from 'moment'

import HmNav from 'components/hm-nav.vue'
import HmHeader from 'components/hm-header.vue'
import Hmpost from 'components/hm-post.vue'

import { Button, Toast, Dialog, Field, RadioGroup, Radio, Uploader, Form, List, Tab, Tabs, PullRefresh, Icon } from 'vant'

Vue.use(Button)
Vue.use(Toast)
Vue.use(Dialog)
Vue.use(Field)
Vue.use(RadioGroup)
Vue.use(Radio)
Vue.use(Uploader)
Vue.use(Form)
Vue.use(List)
Vue.use(Tab)
Vue.use(Tabs)
Vue.use(Icon)
Vue.use(PullRefresh)

Vue.component('HmNav', HmNav)
Vue.component('HmHeader', HmHeader)
Vue.component('HmPost', Hmpost)

Vue.prototype.$axios = axios

axios.defaults.baseURL = 'http://localhost:3000'

// 配置拦截器，
// 添加请求拦截器: 在请求真正发出去之前，都会请求拦截器
axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = token
  }
  console.log(config)
  return config
}, function (error) {
  return Promise.reject(error)
})

axios.interceptors.response.use(function (response) {
  if (response.data.statusCode === 401 && response.data.message === '用户信息验证失败') {
    localStorage.removeItem('user_id')
    localStorage.removeItem('token')
    Toast('登录状态失效，请重新登录')
    // 拦截到登录页
    router.push('/login')
  }
  if (response.data.statusCode === 500) {
    Toast.fail('当前服务器繁忙')
  }
  return response
}, function (error) {
  return Promise.reject(error)
})

Vue.filter('time', function (value) {
  return moment(value).format('YYYY-MM-DD')
})
Vue.filter('fixUrl', function (url) {
  return axios.defaults.baseURL + url
})

Vue.directive('focus', {
  inserted (el, binding) {
    el.focus()
  }
})
Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
